package com.dily.study.demo.entity.jpa.enumdemo;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class EnumConverter implements AttributeConverter<GradeEnum, String> {

	/**
	 * 此方法告诉jpa数据库里存的值
	 */
	@Override
	public String convertToDatabaseColumn(GradeEnum gradeEnum) {
		if (gradeEnum == null) {
			return null;
		}
		return gradeEnum.getDes();
	}

	/**
	 * 此方法告诉Java从数据库里取出的值对应的是哪个enum值
	 */
	@Override
	public GradeEnum convertToEntityAttribute(String des) {
		if (des == null) {
			return null;
		}
		for (GradeEnum gradeEnum : GradeEnum.values()) {
			if (gradeEnum.getDes().equals(des)) {
				return gradeEnum;
			}
		}
		throw new IllegalArgumentException(); // 或者给个默认的enum eg: return Category.UNKNOWN
	}

}
